import { computed, reactive, ref } from "vue";
import type {
  BasicComponent,
  FieldIdIndexType,
  FieldVisibilityState,
  FormConfigType
} from "@/views/formgen/components/GenerateForm/types/form";
import type { LocaleConfig } from "@/views/formgen/components/FormDesign/types";

/**
 * 用户表单状态 Hook
 */
export const useUserForm = () => {
  // 当前标记的题目列表
  const markedQuestionList = ref<string[]>([]);

  // 字段的是否显示状态
  const fieldVisibilityMap = ref<Map<string, FieldVisibilityState>>(new Map());

  // 字段选项或者列显示状态
  const fieldOptionVisibilityMap = ref<Map<string, FieldVisibilityState>>(new Map());
  // 字段逻辑被选中的状态 string 题目id value 选项Id
  const fieldOptionCheckStatusMap = ref<Map<string, Set<string>>>(new Map());

  // 当前表单的所有字段
  const allFields = ref<BasicComponent[]>([]);

  // 当前表单的所有字段的id和index的映射
  const fieldIdIndex = ref<FieldIdIndexType>({});

  // 分页的话记录当前页
  const currentPageNum = ref<number>(1);

  // 扩展信息
  const extractInfo = reactive({
    // 题库抽题题目id列表
    randomQuestionIds: null as string | null,
    // 题库抽题题目id列表
    internalQuestionIds: null as string | null,
    // 白名单信息
    whilteListVal: "",
    // 填写任务id
    taskId: null as string | null,
    // 测评的id
    reviewerKey: "",
    // 渠道 来源
    cl: "",
    // sk 分享填写的key
    sk: "",
    // uk 唯一id 用于代填表单id
    uk: ""
  });

  // 题目id和自定义id映射
  const customIdMap = ref<{ [key: string]: string }>({});

  // 是否需要获取微信信息
  const needGetWechatInfo = ref<boolean>(false);

  // 当前表单数据
  const formModel = ref<{ [key: string]: any }>({});

  // 当前页的表单配置 包含題目等
  const currentPageConfig = ref<FormConfigType | null>(null);

  // 表单提交按钮加载状态
  const submitLoading = ref<boolean>(false);

  // 是否恢复了表单数据
  const isRecoverFormData = ref<boolean>(false);

  // 多语言配置
  const localeConfig = ref<LocaleConfig | null>(null);

  // 当前选中的语言
  const currentLang = ref<string>("");

  // ========== actions ==========

  // 设置题库抽题题目id列表
  const setRandomQuestionIds = (randomId: string, internalId: string) => {
    extractInfo.randomQuestionIds = randomId;
    extractInfo.internalQuestionIds = internalId;
  };

  // 设置白名单信息
  const setWhilteListVal = (val: string) => {
    extractInfo.whilteListVal = val;
  };

  // 设置测评ID
  const setReviewerKey = (key: string) => {
    extractInfo.reviewerKey = key;
  };

  // 合并设置扩展信息
  const setExtractInfo = (partial: Partial<typeof extractInfo>) => {
    Object.assign(extractInfo, partial);
  };

  // 标记或者取消标记题目
  const toggleMarkedQuestion = (questionId: string) => {
    const index = markedQuestionList.value.indexOf(questionId);
    if (index > -1) {
      markedQuestionList.value.splice(index, 1);
    } else {
      markedQuestionList.value.push(questionId);
    }
  };

  // 设置所有字段信息并初始化索引与自定义ID映射
  const setAllFields = (fields: BasicComponent[]) => {
    allFields.value = fields;
    fieldIdIndex.value = {};
    customIdMap.value = {};
    for (let i = 0; i < fields.length; i++) {
      fieldIdIndex.value[fields[i].vModel] = i;
      if (fields[i].customId) {
        customIdMap.value[fields[i].vModel] = fields[i].customId;
      }
    }
    needGetWechatInfo.value = fields.some(item => item.vModel?.includes("goods_select"));
  };

  // 设置当前分页页码
  const setCurrentPage = (num: number) => {
    currentPageNum.value = num;
  };

  // 设置表单数据
  const setFormModel = (model: Record<string, any>) => {
    formModel.value = model || {};
  };

  // 设置表单单个项的数据setFormModelItem setFormModelItem
  const setFormModelItem = (key: string, val: any) => {
    formModel.value[key] = val;
  };

  // 设置当前页的表单配置
  const setCurrentPageConfig = (config: FormConfigType) => {
    currentPageConfig.value = config;
  };

  // 设置是否恢复了表单数据
  const setIsRecoverFormData = (flag: boolean) => {
    isRecoverFormData.value = flag;
  };

  // 设置多语言配置
  const setLocaleConfig = (config: LocaleConfig) => {
    localeConfig.value = config;
  };

  // 设置当前语言
  const setCurrentLang = (lang: string) => {
    currentLang.value = lang;
  };

  // 页面是否分页
  const isPageForm = computed(() => {
    return currentPageConfig.value?.perPageFields && Object.keys(currentPageConfig.value.perPageFields)?.length > 0;
  });

  return {
    // state 暴露
    markedQuestionList,
    fieldVisibilityMap,
    fieldOptionVisibilityMap,
    fieldOptionCheckStatusMap,
    allFields,
    fieldIdIndex,
    currentPageNum,
    extractInfo,
    customIdMap,
    needGetWechatInfo,
    formModel,
    currentPageConfig,
    submitLoading,
    isRecoverFormData,
    localeConfig,
    currentLang,

    // actions 暴露
    setRandomQuestionIds,
    setWhilteListVal,
    setReviewerKey,
    setExtractInfo,
    toggleMarkedQuestion,
    setAllFields,
    setCurrentPage,
    setFormModel,
    setFormModelItem,
    setCurrentPageConfig,
    setIsRecoverFormData,
    setLocaleConfig,
    setCurrentLang,
    isPageForm
  };
};

export type ReturnTypeOfUseUserForm = ReturnType<typeof useUserForm>;
